"""
系统配置使用示例
展示如何在代码中使用系统配置
"""
from app.modules.system.services import SystemConfigService


class ConfigExample:
    """系统配置使用示例类"""
    
    @staticmethod
    async def example_usage():
        """使用示例"""
        
        # 1. 获取配置值（带类型转换）
        site_name = await SystemConfigService.get_config_value("site_name", "默认站点名")
        max_upload_size = await SystemConfigService.get_config_value("upload_max_size", 10485760)
        enable_registration = await SystemConfigService.get_config_value("enable_registration", True)
        
        print(f"站点名称: {site_name}")
        print(f"最大上传大小: {max_upload_size} 字节")
        print(f"是否启用注册: {enable_registration}")
        
        # 2. 设置配置值
        await SystemConfigService.set_config_value(
            key="custom_setting",
            value="自定义配置值",
            description="这是一个自定义配置",
            config_type="string",
            is_system=False,
            is_public=True
        )
        
        # 3. 设置复杂配置（JSON类型）
        email_config = {
            "smtp_host": "smtp.qq.com",
            "smtp_port": 587,
            "username": "admin@example.com",
            "use_tls": True
        }
        
        await SystemConfigService.set_config_value(
            key="email_config",
            value=email_config,
            description="邮件服务器配置",
            config_type="json",
            is_system=True,
            is_public=False
        )
        
        # 4. 获取JSON配置
        email_settings = await SystemConfigService.get_config_value("email_config", {})
        print(f"邮件配置: {email_settings}")


class ConfigMiddlewareExample:
    """配置中间件示例"""
    
    @staticmethod
    async def maintenance_mode_check():
        """维护模式检查示例"""
        maintenance_mode = await SystemConfigService.get_config_value("maintenance_mode", False)
        
        if maintenance_mode:
            maintenance_message = await SystemConfigService.get_config_value(
                "maintenance_message", 
                "系统维护中，请稍后再试"
            )
            return {
                "status": "maintenance",
                "message": maintenance_message
            }
        
        return {"status": "normal"}


class ConfigValidationExample:
    """配置验证示例"""
    
    @staticmethod
    async def validate_upload_file(file_size: int, file_extension: str):
        """验证文件上传"""
        # 获取配置
        max_size = await SystemConfigService.get_config_value("upload_max_size", 10485760)
        allowed_extensions = await SystemConfigService.get_config_value(
            "upload_allowed_extensions", 
            ["jpg", "jpeg", "png", "gif"]
        )
        
        # 验证文件大小
        if file_size > max_size:
            raise ValueError(f"文件大小超过限制: {max_size} 字节")
        
        # 验证文件扩展名
        if file_extension.lower() not in [ext.lower() for ext in allowed_extensions]:
            raise ValueError(f"不支持的文件类型: {file_extension}")
        
        return True


class ConfigCacheExample:
    """配置缓存示例"""
    
    @staticmethod
    async def get_cached_config(key: str, default=None):
        """获取缓存的配置（示例）"""
        # 检查是否启用缓存
        cache_enabled = await SystemConfigService.get_config_value("cache_enabled", True)
        
        if cache_enabled:
            # 这里可以集成Redis等缓存系统
            # 示例：从缓存获取配置
            pass
        
        # 从数据库获取配置
        return await SystemConfigService.get_config_value(key, default)


# 使用示例
async def main():
    """主函数示例"""
    example = ConfigExample()
    await example.example_usage()
    
    # 维护模式检查
    maintenance_check = ConfigMiddlewareExample()
    status = await maintenance_check.maintenance_mode_check()
    print(f"系统状态: {status}")
    
    # 文件上传验证
    validation = ConfigValidationExample()
    try:
        await validation.validate_upload_file(1024 * 1024, "jpg")  # 1MB的jpg文件
        print("文件验证通过")
    except ValueError as e:
        print(f"文件验证失败: {e}")


if __name__ == "__main__":
    import asyncio
    asyncio.run(main()) 